'use strict';

const Controller = require('egg').Controller;

const createRule = {
  shopId: {
    type: 'int',
    required: true,
    min: 1
  },
  comment: {
    type: 'string',
    allowEmpty: true,
    max: 255
  },
  systemComment: {
    type: 'string',
    allowEmpty: true,
    max: 255
  },
  productList: {
    type: 'array',
    itemType: 'object',
    required: true,
    rule: {
      productId: 'int',
      number: 'int',
      priceIndex: 'int'
    },
    min: 1,
    max: 8
  }
};

class OrdersController extends Controller {
  async index () {
    // const userId = this.ctx.state.user.id;
    const userId = this.ctx.state.user.id;

    // const shopId = this.ctx._subId;
    // const shopId = 10;
    const number = this.ctx.query.number ? this.ctx.query.number : 1;

    const size = this.ctx.query.size ? this.ctx.query.size : 10;
    const filters = {
      userId
      // shopId
    };

    const pages = {
      number,
      size
    };
    const orders = await this.service.orders.index(filters, pages);

    this.ctx.body = orders;
  }

  async create () {
    this.ctx.validate(createRule);

    const userId = this.ctx.state.user.id;
    const shopId = this.ctx.request.body.shopId;
    const comment = this.ctx.request.body.comment;
    const productList = this.ctx.request.body.productList;
    const systemComment = this.ctx.request.body.systemComment;
    // const userId = 17;
    // const shopId = 10;
    // const comment = '';
    // let productList = [{
    //   productId: 76,
    //   number: 2,
    //   priceIndex: 0
    // }];
    // const source = 2;
    const { order } = await this.service.orders.create(userId, shopId, comment, productList, systemComment);
    if (order === null) {
      this.ctx.status = 404;
      this.ctx.body = {};
    } else {
      this.ctx.status = 201;
      this.ctx.body = {
        order
      };
    }
  }

  async show () {
    // 订单id
    const id = this.ctx.params.id;
    const {
      order,
      productSnapshots
    } = await this.service.orders.show(id);
    if (order === null) {
      this.ctx.status = 404;
      this.ctx.body = {};
    } else {
      this.ctx.body = {
        order,
        productSnapshots
      };
    }
  }

  async pay () {
    const id = this.ctx.params.id;
    // const payType = 1;
    // const payComment = [];
    const payType = this.ctx.request.body.payType;
    const payComment = this.ctx.request.body.payComment;

    const pay = await this.service.orders.pay(id, payType, payComment);
    this.ctx.body = pay;
  }
}

module.exports = OrdersController;
